#ifndef _MYSQL_WRAPPER_H_
#define _MYSQL_WRAPPER_H_

#include <string>
#include <vector>
#include <map>
#ifdef WIN32
#include <windows.h>
#endif
#include <mysql.h>

class CMysqlWrapper
{
public:
	CMysqlWrapper()
	{
		m_conn = mysql_init(NULL);
	}
	virtual ~CMysqlWrapper()
	{
		if(m_conn != NULL)
		{
			mysql_close(m_conn);
			m_conn = NULL;
		}
	}
	virtual bool init(const std::string sIp, int port, const std::string& sUser, const std::string& sPwd, const std::string& sDbName)
	{
		if (mysql_real_connect(m_conn, sIp.c_str(), sUser.c_str(), 
			sPwd.c_str(), sDbName.c_str(), port, NULL, 0) == NULL) 
		{
			return false;
		}
		return true;
	}

	int excute(const std::string& sSql)
	{
		if(m_conn == NULL) return -1;
		mysql_query(m_conn, sSql.c_str());
		return (int)mysql_affected_rows(m_conn);
	}

	template<class T>
	int excuteSelect(const std::string& sSql, T func)
	{
		if(m_conn == NULL) return -1;
		if(mysql_query(m_conn, sSql.c_str()) == 0)
		{
			MYSQL_RES *result;
			MYSQL_ROW row;
			result = mysql_store_result(m_conn);
			while ((row = mysql_fetch_row(result)))
			{
				unsigned long *lengths;
				lengths = mysql_fetch_lengths(result);
				func(row, lengths);
			}
			mysql_free_result(result);
			return 0;
		}
		return -1;
	}

	int getLastError(std::string& sError)
	{
		sError = mysql_error(m_conn);
		return mysql_errno(m_conn);
	}
protected:
	
private:
	MYSQL* m_conn;
};

#endif // _MYSQL_WRAPPER_H_